//
//  PhoneRegisterViewController.m
//  SoundPill
//
//  Created by 温冬 on 15/5/1.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "PhoneRegisterViewController.h"
#import "registryEditController.h"
#import "AFNetworking.h"
#import "AppDelegate.h"
#import "JCAlertView.h"
#import <CoreLocation/CoreLocation.h>
#define IOS8 [[[UIDevice currentDevice]systemVersion] floatValue] >= 8.0
@interface PhoneRegisterViewController () <CLLocationManagerDelegate>
{
    NSNumber *isRegisted;
    CLLocationManager *_locationManager;
    CLGeocoder *_geocoder;
    NSString *_location;
}
@end

@implementation PhoneRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    ooo = 0;
    [self.view setBackgroundColor:[UIColor whiteColor]];

    self.registerView = [[Register alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view addSubview:self.registerView];
    self.registerView.telNumber.field.delegate = self;
    _registerView.telNumber.field.returnKeyType = UIReturnKeyNext;
    self.registerView.password.field.delegate = self;
        _registerView.password.field.returnKeyType = UIReturnKeyNext;
    self.registerView.repeatPassword.field.delegate = self;
        _registerView.repeatPassword.field.returnKeyType = UIReturnKeyDone;
    self.registerView.securitycode.delegate = self;
        _registerView.securitycode.returnKeyType = UIReturnKeyNext;
    [self.registerView.close addTarget:self action:@selector(closes:) forControlEvents:UIControlEventTouchUpInside];
    [self.registerView.certain addTarget:self action:@selector(certainUserinfo:) forControlEvents:UIControlEventTouchUpInside];
    [self.registerView.timeButton addTarget:self action:@selector(startTime:) forControlEvents:UIControlEventTouchUpInside];
    
    //定位管理器
    _locationManager=[[CLLocationManager alloc]init];
    if (![CLLocationManager locationServicesEnabled]) {
//        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
        return;
    }
    //如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
        if (IOS8) {
            [_locationManager requestWhenInUseAuthorization];
        }
    }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
        //设置代理
        _locationManager.delegate=self;
        //设置定位精度
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        //定位频率,每隔多少米定位一次
        CLLocationDistance distance = 10.0;//十米定位一次
        _locationManager.distanceFilter=distance;
        //启动跟踪定位
        [_locationManager startUpdatingLocation];
    }
}
#pragma mark - CoreLocation 代理
#pragma mark 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）
//可以通过模拟器设置一个虚拟位置，否则在模拟器中无法调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=[locations lastObject];//取出第一个位置
    CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
//    NSLog(@"经度：%f,纬度：%f,海拔：%f,航向：%f,行走速度：%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    //根据经纬度反向地理编译出地址信息
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *array, NSError *error)
    {
        if (array.count > 0)
        {
            CLPlacemark *placemark = [array objectAtIndex:0];
            _location = [NSString stringWithFormat:@"%@  %@", placemark.locality, placemark.subLocality];
//            NSLog(@"%@,%@",placemark.subLocality, placemark.locality);
        }
    }];
    //如果不需要实时定位，使用完即使关闭定位服务
    [_locationManager stopUpdatingLocation];
}

- (void)closes:(UIButton *)button
{
    [self resignAllResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)certainUserinfo:(UIButton *)button
{
    if (self.registerView.securitycode.text.length == 0){
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"验证码不能为空";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"验证码不能为空" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [alertView show];
//        [self performSelector:@selector(registDismissAlert:) withObject:alertView afterDelay:1.5];
    }else{
//        将用户注册信息上传到服务器
        [self uploading];
    }
}

- (void)registDismissAlert:(UIAlertView *)alertView
{
    if (alertView) {
        [alertView dismissWithClickedButtonIndex:[alertView cancelButtonIndex] animated:YES];
        [self resignAllResponder];
    }
}

#pragma mark - 判断手机格式是否正确
- (void)startTime:(UIButton *)button
{
//    NSString *phoneRegex = @"^((177)|(13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
//    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    BOOL isUser;//= [phoneTest evaluateWithObject:self.registerView.telNumber.field.text];
    if (self.registerView.telNumber.field.text.length == 11) {
        isUser = YES;
    } else {
        isUser = NO;
    }
    if (isUser == YES)
    {
//        _registerView.timeButton.userInteractionEnabled = NO;
        self.registerView.timeLabel.hidden = YES;
        self.registerView.timeButton.hidden = NO;
        [self.registerView.securitycode becomeFirstResponder];
        [self requsetSecurityCode];
    }
    else{
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"手机号格式不正确" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [alertView show];
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"手机号格式不正确";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
//        [self performSelector:@selector(resignAllResponder) withObject:nil afterDelay:0.5];
        [self resignAllResponder];
        [self.registerView.telNumber.field becomeFirstResponder];
    }
}

#pragma mark - 验证码倒计时
- (void)createCountDown
{
    __block int timeout = 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.registerView.timeLabel.hidden = YES;
                [self.registerView.timeButton setTitle:@"重新获取" forState:UIControlStateNormal];
                self.registerView.timeButton.hidden = NO;
                self.registerView.timeButton.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout % 61;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.registerView.timeLabel.hidden = NO;
                self.registerView.timeLabel.text = [NSString stringWithFormat:@"剩余%@秒",strTime];
                self.registerView.timeLabel.textAlignment = NSTextAlignmentCenter;
                self.registerView.timeButton.hidden = YES;
                self.registerView.timeButton.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - 请求云片发送验证码
- (void)requsetSecurityCode
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/sendsms"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:self.registerView.telNumber.field.text, @"mobile", @"register", @"type", nil];
    [manager POST:url parameters:data progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self createCountDown];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark - 上传用户信息到服务器
- (void)uploading
{
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/register"];
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:self.registerView.telNumber.field.text, @"mobile", self.registerView.password.field.text, @"password", self.registerView.securitycode.text, @"code", [AppDelegate shareDelegate].deviceToken, @"deviceToken", nil];
    [manager POST:url parameters:data progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [netWorkManager stopMonitoring];
        
        registryEditController *userVC = [[registryEditController alloc]init];
        userVC.locationStr = _location;
        UINavigationController *userNav = [[UINavigationController alloc] initWithRootViewController:userVC];
        [self presentViewController:userNav animated:YES completion:nil];
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"注册成功";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [self performSelector:@selector(resignAllResponder) withObject: nil afterDelay:1.5];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
        
        NSDictionary *dic = responseObject;
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString *token = [NSString stringWithFormat:@"%@",[dic objectForKey:@"token"]];
        NSString *uid = [NSString stringWithFormat:@"%@",[dic objectForKey:@"uid"]];
        [user setObject:token forKey:@"token"];
        [user setObject:uid forKey:@"uid"];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
        customView.backgroundColor = [UIColor whiteColor];
        customView.text = @"验证码不正确";
        customView.textAlignment = NSTextAlignmentCenter;
        customView.layer.borderColor = [[UIColor blackColor] CGColor];
        customView.layer.borderWidth = 2;
        JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
        [_alert show];
        [self performSelector:@selector(resignAllResponder) withObject:nil afterDelay:1.5];
        [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
        
    }];
}
#pragma mark - 点击完成按钮  注册
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == _registerView.telNumber.field) {
        if (textField.text.length > 0) {
            NSString *phoneRegex = @"^((177)|(13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
            NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
            BOOL isUser = [phoneTest evaluateWithObject:self.registerView.telNumber.field.text];
            if (isUser == NO){
                UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
                customView.backgroundColor = [UIColor whiteColor];
                customView.text = @"手机号格式不正确";
                customView.textAlignment = NSTextAlignmentCenter;
                customView.layer.borderColor = [[UIColor blackColor] CGColor];
                customView.layer.borderWidth = 2;
                JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
                [_alert show];
                [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
//                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"手机格式不正确" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//                [alertView show];
                [self performSelector:@selector(resignAllResponder) withObject: nil afterDelay:1.5];
            } else {
                isRegisted = [NSNumber numberWithBool:NO];
                //验证手机号是否已注册
                if (isRegisted.boolValue == NO) {
                    [self isRegistedWithPhoneNum:textField.text];
                }
            }
        }
    } else if (textField == _registerView.password.field) {
        if (textField.text.length < 6 && textField.text.length > 0) {
            _registerView.repeatPassword.field.text = @"";
            _registerView.password.field.text = @"";
            UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
            customView.backgroundColor = [UIColor whiteColor];
            customView.text = @"密码位数不正确,至少6位";
            customView.textAlignment = NSTextAlignmentCenter;
            customView.layer.borderColor = [[UIColor blackColor] CGColor];
            customView.layer.borderWidth = 2;
            JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
            [_alert show];
            [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
            [self performSelector:@selector(resignAllResponder) withObject:nil afterDelay:1.5];

        }
    } else if (textField == _registerView.repeatPassword.field){
        if (_registerView.password.field.text.length > 0 && _registerView.repeatPassword.field.text.length > 0) {
            if (![_registerView.repeatPassword.field.text isEqualToString:_registerView.password.field.text]) {
                
                UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
                customView.backgroundColor = [UIColor whiteColor];
                customView.text = @"两次输入的密码不相同，请重新输入";
                customView.textAlignment = NSTextAlignmentCenter;
                customView.layer.borderColor = [[UIColor blackColor] CGColor];
                customView.layer.borderWidth = 2;
                JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
                [_alert show];
                [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
                [self performSelector:@selector(resignAllResponder) withObject:nil afterDelay:1.5];
                
//                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"两次输入的密码不相同，请重新输入" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
//                [alertView show];
//                [self performSelector:@selector(registDismissAlert:) withObject:alertView afterDelay:1.5];
                
            }
        }
    } //else if (textField == _registerView.securitycode) {
        
    //}
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _registerView.telNumber.field) {
        [_registerView.securitycode becomeFirstResponder];
    } else if (textField == _registerView.securitycode) {
        [_registerView.password.field becomeFirstResponder];
    } else if (textField == _registerView.password.field) {
        [_registerView.repeatPassword.field becomeFirstResponder];
    } else {
        if (self.registerView.securitycode.text.length == 0){
            UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
            customView.backgroundColor = [UIColor whiteColor];
            customView.text = @"验证码不能为空";
            customView.textAlignment = NSTextAlignmentCenter;
            customView.layer.borderColor = [[UIColor blackColor] CGColor];
            customView.layer.borderWidth = 2;
            JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
            [_alert show];
            [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
            [self performSelector:@selector(resignAllResponder) withObject:nil afterDelay:1.5];
        }else{
            //将用户注册信息上传到服务器
            [self uploading];
        }
    }
    return YES;
}
- (void)isRegistedWithPhoneNum:(NSString *)num
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/isexist?mobile=%@", num];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        if ([[dic valueForKey:@"mobile"] isEqualToString:@"0"]) {
            UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
            customView.backgroundColor = [UIColor whiteColor];
            customView.text = @"该手机号已被注册";
            customView.textAlignment = NSTextAlignmentCenter;
            customView.layer.borderColor = [[UIColor blackColor] CGColor];
            customView.layer.borderWidth = 2;
            JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
            [_alert show];
            [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
            //            [self performSelector:@selector(resignAllResponder) withObject:nil afterDelay:1.5];
            [self resignAllResponder];
            [self.registerView.telNumber.field becomeFirstResponder];
            //            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"该手机号已被注册" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
            //            [alert show];
            //            [self performSelector:@selector(registDismissAlert:) withObject:alert afterDelay:1.5];
            
            isRegisted = [NSNumber numberWithBool:NO];
        } else {
            isRegisted = [NSNumber numberWithBool:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark - 回收键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//    [self resignAllResponder];
}
- (void)resignAllResponder
{
    [self.registerView.telNumber.field resignFirstResponder];
    [self.registerView.password.field resignFirstResponder];
    [self.registerView.repeatPassword.field resignFirstResponder];
    [self.registerView.securitycode resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
